package com.ocean.weixin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocean.weixin.utils.HttpUtils;
import com.ocean.weixin.utils.SignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @auther DLY
 * @create 2017/9/22
 */

@Controller
public class WeixinController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final static String APPID = "wxc63edcf67a00e70c";
    private final static String SECRET = "fb02b553990a1ffd3535431be488faa0";
    /*
    * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc63edcf67a00e70c&redirect_uri=http://h.nabaiuf.com/auth&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
    * */

    @GetMapping(value = "/download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {

        // Enumeration<String> headerNames = request.getHeaderNames();
        // while (headerNames.hasMoreElements()) {
        //     String element = headerNames.nextElement();
        //     String header = request.getHeader(element);
        //     logger.info("\n key:{}, value:{}", element, header);
        // }
        // 取分享人的uid
        String uid = request.getParameter("uid");
        logger.info("\n ====> uid:{}, ", uid);


        String tempScope = "snsapi_base";
        String first = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc63edcf67a00e70c"
            + "&redirect_uri=http://h.nabaiuf.com/auth&response_type=code&scope=%s&state=STATE#wechat_redirect";

        response.sendRedirect(String.format(first,tempScope));

        // logger.info("\n ====> 返回响应:{}", responseMsg);
        //
        // JSONObject jsonObject = JSON.parseObject(responseMsg);
        // Object errcode = jsonObject.get("errcode");
        // if (Objects.nonNull(errcode) && Objects.equals(errcode, 48001)) {
        //     tempScope = "snsapi_userinfo";
        //     HttpUtils.sendGetRequest(String.format(tempScope), null);
        // } else if (Objects.isNull(errcode)){
        //     response.sendRedirect("/download.html");
        // } else {
        //     logger.info("\n ====> 其他响应");
        // }
    }

    @GetMapping(value = "/auth")
    @ResponseBody
    public String redirectUri(HttpServletRequest request) throws Exception {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        Objects.requireNonNull(code);
        Objects.requireNonNull(state);

        logger.info("\n ====> code:{}, state:{}", code, state);

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
            "appid=" + APPID + "&secret=" + SECRET + "&code=" + code + "&grant_type=authorization_code";

        // 响应
        String response = HttpUtils.sendGetRequest(url, null);
        logger.info("\n ====> 返回信息:{}", response);
        Objects.requireNonNull(response);

        // {"errcode":40029,"errmsg":"invalid code"}

        JSONObject object = JSON.parseObject(response);

        Object errcode = object.get("errcode");

        if (Objects.nonNull(errcode)) {
            logger.info("\n ==111111==> 异常返回");
            throw new RuntimeException("错误返回");
        }

        String accessToken = (String) object.get("access_token");
        String refreshToken = (String) object.get("refresh_token");
        String openid = (String) object.get("openid");
        String scope = (String) object.get("scope");

        logger.info("\n ====>accessToken:{}, refreshToken:{}, openid:{}, scope:{}",
            accessToken, refreshToken, openid, scope);

        url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openid + "&lang=zh_CN";
        response = HttpUtils.sendGetRequest(url, null);
        logger.info("\n ====> 返回信息:{}", response);

        object = JSON.parseObject(response);
        errcode = object.get("errcode");
        if (Objects.nonNull(errcode)) {
            logger.info("\n ==2222222==> 异常返回");
            throw new RuntimeException("错误返回");
        }
        return "download";
    }


    @GetMapping(value = "/")
    @ResponseBody
    public String index(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        logger.info("[signature: " + signature + "]<-->[timestamp: " + timestamp + "]<-->[nonce: " +
            nonce + "]<-->[echostr: " + echostr + "]");
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            return echostr;
        }
        return "失败返回";
    }

    public static void main(String[] args) {

        String temp = "11";
        String result = "=====> %s";

        System.out.println(String.format(result, temp));

    }

}
